package com.kkwrite.regimen.consumer.controller.captcha;

import com.kkwrite.regimen.common.entity.dto.OutDTO;
import com.kkwrite.regimen.common.entity.dto.captcha.CaptchaQuery;
import com.kkwrite.regimen.common.entity.dto.captcha.CodeDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

import static com.kkwrite.regimen.common.constant.Constant.BOOLEAN_STRING_FALSE;
import static com.kkwrite.regimen.consumer.controller.constant.Constant.SERVICE_PREFIX;

/**
 * 验证码模块
 *
 * @author Soosky Wang
 * @version 1.0.0
 * @date 2018年7月19日 上午11:49:48
 */
@Api(value = "验证码模块")
@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    private static final Logger logger = LoggerFactory.getLogger(CaptchaController.class);

    @Resource(name = "restTemplate")
    private RestTemplate restTemplate;

    /**
     * @param phoneNum 手机号
     * @return OutDTO
     */
    @ApiOperation(value = "获取手机验证码")
    @ApiImplicitParams(
            {@ApiImplicitParam(name = "phoneNum", value = "手机号码", required = true, paramType = "path", dataType = "string")}
    )
    @GetMapping("/getmsgcaptcha/{phoneNum}")
    public OutDTO getMsgCaptcha(@PathVariable String phoneNum) {
        if (logger.isDebugEnabled()) {
            logger.debug("CaptchaController.getMsgCaptcha(), phoneNum = {}", phoneNum);
        }

        CaptchaQuery captchaQuery = new CaptchaQuery();
        captchaQuery.setCaptchaSource(phoneNum);
        try {
            String url = SERVICE_PREFIX + "/captcha/getcaptcha?captchaSource=" + phoneNum;
            return restTemplate.getForObject(url, CodeDTO.class);
        } catch (RestClientException e) {
            logger.error("查询验证码出错，phoneNum = " + phoneNum + "_" + e.getMessage(), e);
            return OutDTO.of(BOOLEAN_STRING_FALSE, "查询短信验证码出错！");
        }
    }

}
